package com.guyan.controller;

import com.github.pagehelper.PageInfo;
import com.guyan.entity.Cart;
import com.guyan.form.CartForm;
import com.guyan.service.CartService;
import com.guyan.vo.LayuiVo;
import com.guyan.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * ClassName： CartController
 * Date： 2021/6/14 15:08
 *
 * @author 孤焰
 * @version 1.0
 **/

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @GetMapping("/cartList")
    public LayuiVo cartList(@RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer limit,
                            Integer userId) {
        PageInfo pageInfo = cartService.cartList(page, limit, userId);

        return LayuiVo.success(pageInfo.getTotal(), pageInfo.getList());
    }

    @PostMapping("/updateCartById")
    public ResultVo updateCartById(@RequestBody Cart cart) {
        return cartService.updateCartById(cart);
    }

    @PostMapping("/addCart")
    public ResultVo addCart(@RequestBody @Valid CartForm cartForm, BindingResult bindingResult) {
        if (bindingResult.getErrorCount() > 0) {
            return ResultVo.error(7000, bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        Cart cart = new Cart();
        BeanUtils.copyProperties(cartForm, cart);

        return cartService.addCart(cart);
    }

    @PostMapping("/batchDelCart")
    public ResultVo batchDelCart(@RequestBody Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return ResultVo.error(5001, "未选择要删除的产品");
        }

        return cartService.batchDelCart(ids);
    }

}
